package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @author 虎哥
 */
@Slf4j
@Component
public class AuthFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private JwtProperties prop;

    @Autowired
    private FilterProperties filterProp;

    /**
     * 过滤器类型，前置
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    /**
     * @return true：run方法会被执行。false：不执行run方法
     */
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String path = request.getRequestURI();
        boolean isAllow  = isAllowPath(path);
        return !isAllow;
    }

    private boolean isAllowPath(String path) {
        List<String> allowPaths = filterProp.getAllowPaths();
        for (String allowPath : allowPaths) {
            if (path.startsWith(allowPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = currentContext.getRequest();
        //1.从cookie中得到token
        String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());

        try {
            //2.解析token
            Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            //获取token的id
            String id = infoFromToken.getId();
            //在黑名单中检索是否存在
            Boolean aBoolean = redisTemplate.hasKey(id);
            if (aBoolean != null && aBoolean) {
                // 证明存在与黑名单，说明token已经登出过，无效
                throw new RuntimeException("token已经登出，是无效token");
            }
        } catch (RuntimeException e) {
            //拦截请求
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(403);
            log.error("非法访问，未登录，地址：{}", request.getRemoteHost(), e);
        }
        return null;
    }
}